package com.bmps.springcloud.insuredmicroservice.service.underwrite.strategy.minordeath.riskstrategy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description:
 * 险种策略工厂
 *
 * @author jackdaw
 * @date 2020-01-07 10:29
 */

@Component
public class RiskStrategyFactory {
    private Logger logger = LoggerFactory.getLogger(RiskStrategyFactory.class);

    private final static ConcurrentHashMap<String, RiskStrategy> RISK_STRATEGY_MAP = new ConcurrentHashMap<>();

    public RiskStrategyFactory(Map<String, RiskStrategy> riskStrategyMap) {
        RiskStrategyFactory.RISK_STRATEGY_MAP.clear();
        //riskStrategyMap.forEach(RiskStrategyFactory.riskStrategyMap::put);
        try {
            Resource resource = new ClassPathResource("minordeathriskstrategy.properties");
            InputStream inputStream = resource.getInputStream();
            Properties properties = new Properties();
            properties.load(inputStream);
            for (String key : properties.stringPropertyNames()) {
                RiskStrategy strategy = riskStrategyMap.get(properties.getProperty(key));
                Arrays.stream(key.split(",")).forEach(s -> {
                    RISK_STRATEGY_MAP.put(s, strategy);
                    logger.info("riskStrategyMap add key: " + s + ", new instance:" + strategy);
                });
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public static RiskStrategy getInsuranceStrategy(String key) {
        return RISK_STRATEGY_MAP.get(key);
    }
}
